package cn.stylefeng.guns.modular.rest;


import cn.hutool.core.date.DateUtil;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.comm.util.DateUtils;
import cn.stylefeng.guns.modular.ht.entity.BackRegister;
import cn.stylefeng.guns.modular.ht.entity.Report;
import cn.stylefeng.guns.modular.ht.model.params.BackRegisterParam;
import cn.stylefeng.guns.modular.ht.model.params.ReportParam;
import cn.stylefeng.guns.modular.ht.model.result.ReportResult;
import cn.stylefeng.guns.modular.ht.service.BackRegisterService;
import cn.stylefeng.guns.modular.ht.service.ReportService;
import cn.stylefeng.guns.sys.core.constant.factory.ConstantFactory;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.SuccessResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.tools.Tool;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 绑定控制器
 *
 * @author
 * @Date 2019-11-18 13:24:11
 */
@RestController
@RequestMapping("/gunsApi/static")
public class ApiNeedTokenStaticController extends BaseController {
    @Autowired
    private ReportService reportService;
    @Autowired
    private BackRegisterService backRegisterService;
    @Autowired
    private UserService userService;

    /**
     * 绑定
     */
    @RequestMapping(value = "")
    public Object index(String username) {
        String today = DateUtil.today();
        String tomorrow = DateUtil.format(DateUtil.tomorrow(), "yyyy-MM-dd");
        Map map = new HashMap();
        SuccessResponseData SUCCESS_TIP = new SuccessResponseData();

        // 查找当前登录用户除了【顶层】外所有父子部门ID。
        List<Long> deptIdsWithoutTop = getDeptIdsWithoutTop(username);
        ReportParam reportParam = new ReportParam();
        reportParam.setDeptIds(deptIdsWithoutTop);
        reportParam.setToday(today);

        // 总人数
        int total = userService.count(new QueryWrapper<User>().eq("status", "ENABLE").in("dept_id", deptIdsWithoutTop));
        // 健康人数
        int healthyCount = reportService.countHealthy(reportParam);
        // 异常人数
        int alertCount = reportService.countAlert(reportParam);
        // 已上报人员名单
        List<ReportResult> reportList = reportService.allReportedList(reportParam);
        LayuiPageInfo reporteds = reportService.findReporteds(reportParam);
        List<ReportResult> reportResultList = reporteds.getData();
        // 当日已上报人数
        long reportCount = reporteds.getCount();
        // 未上报人员名单
        List<String> reportAccounts = new ArrayList<>();
        reportList.forEach(report -> {
            // 已上报账户
            reportAccounts.add(report.getAccount());
        });
        reportResultList.forEach(report -> {
            report.setReportTimeStr(DateUtils.format(report.getReportTime()));
        });
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<User>().eq("status", "ENABLE").in("dept_id", deptIdsWithoutTop);
        if (reportAccounts.size() > 0)
            userQueryWrapper.notIn("account", reportAccounts);
        List<User> notReportUsers = userService.list(userQueryWrapper);

        // 返程登记人员信息
        BackRegisterParam backRegisterParam = new BackRegisterParam();
        backRegisterParam.setDeptIds(deptIdsWithoutTop);
        LayuiPageInfo backRegisterList = backRegisterService.findPageBySpecForApi(backRegisterParam);


        map.put("now", DateUtil.now());
        map.put("total", total);
        map.put("reportCount", reportCount);
        map.put("healthyCount", healthyCount);
        map.put("alertCount", alertCount);
        map.put("reportList", reportResultList);
        map.put("notReportUsers", notReportUsers);
        map.put("backRegisterList", backRegisterList.getData());
        map.put("backRegisterList_count", backRegisterList.getCount());
        SUCCESS_TIP.setData(map);
        return SUCCESS_TIP;
    }

    private List<Long> getDeptIdsWithoutTop(String username) {
        User currentUser = userService.getByAccount(username);
        List<Long> parentDeptIds = ConstantFactory.me().getParentDeptIds(currentUser.getDeptId());
        List<Long> subDeptIds = ConstantFactory.me().getSubDeptId(currentUser.getDeptId());
        List<Long> deptIdsWithoutTop = new ArrayList<>();
        deptIdsWithoutTop.add(currentUser.getDeptId());
        parentDeptIds.forEach(deptId -> {
            if (deptId != 0) {
                deptIdsWithoutTop.add(deptId);
            }
        });
        subDeptIds.forEach(deptId -> {
            deptIdsWithoutTop.add(deptId);
        });
        return deptIdsWithoutTop;
    }

    @RequestMapping(value = "history")
    public Object history(String username) {
        Map map = new HashMap();
        SuccessResponseData SUCCESS_TIP = new SuccessResponseData();

        List<Report> reportList = reportService.list(new QueryWrapper<Report>().eq("account", username).orderByDesc("id"));
        List<ReportResult> reportResultList = new ArrayList<>();
        reportList.forEach(report -> {
            ReportResult reportResult = new ReportResult();
            ToolUtil.copyProperties(report, reportResult);
            reportResult.setReportTimeStr(DateUtils.format(reportResult.getReportTime()));
            reportResultList.add(reportResult);
        });
        map.put("reportList", reportResultList);

        SUCCESS_TIP.setData(map);
        return SUCCESS_TIP;
    }

    /**
     * 绑定
     */
    @RequestMapping(value = "loadmore")
    public Object loadMore(String reportFlag, String username) {
        Map map = new HashMap();
        SuccessResponseData SUCCESS_TIP = new SuccessResponseData();
        if (StringUtils.equals(reportFlag, "report")) {
            ReportParam reportParam = new ReportParam();
            reportParam.setDeptIds(getDeptIdsWithoutTop(username));
            List<ReportResult> reportList = reportService.findReporteds(reportParam).getData();
            reportList.forEach(reportResult -> {
                User user = userService.getByAccount(reportResult.getAccount());
                reportResult.setName(user.getName());
                reportResult.setWxAvatar(user.getWxAvatar());
                reportResult.setReportTimeStr(DateUtils.format(reportResult.getReportTime()));
            });
            map.put("reportList", reportList);
        } else if (StringUtils.equals(reportFlag, "back")) {
            // 返程登记人员信息
            BackRegisterParam backRegisterParam = new BackRegisterParam();
            backRegisterParam.setDeptIds(getDeptIdsWithoutTop(username));
            LayuiPageInfo backRegisterList = backRegisterService.findPageBySpecForApi(backRegisterParam);
            map.put("reportList", backRegisterList.getData());
        }

        SUCCESS_TIP.setData(map);
        return SUCCESS_TIP;
    }
}


